package com.jielihaofeng.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jielihaofeng.shop.common.Result;
import com.jielihaofeng.shop.common.StatusCode;
import com.jielihaofeng.shop.pojo.User;
import com.jielihaofeng.shop.service.UserService;
import com.jielihaofeng.shop.util.BCrypt;
import com.jielihaofeng.shop.security.security.TokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 登录接口
 * </p>
 *
 * @author Johnnie Wind
 * @since 2021-02-25
 */
@RestController
@RequestMapping("")
public class LoginController {

    @Autowired
    TokenProvider tokenProvider;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password) {

        // 根据用户名查找用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>().eq("username",username);
        User user = userService.getOne(userQueryWrapper);
        if (user==null){
            return new Result().msg("登陆失败，用户不存在！").status(StatusCode.BAD_REQUEST);
        }
        // 验证密码
        boolean matches = bCryptPasswordEncoder.matches(password, user.getPassword());
        if (!matches){
            return new Result().msg("登陆失败，密码不正确！").status(StatusCode.BAD_REQUEST);
        }

        // 生成token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", username);
        map.put("password", password);
        String token = tokenProvider.createToken(null);


        map.put("id", 500);
        map.put("rid", 0);
        map.put("mobile", "18570945238");
        map.put("email", "949394048@qq.com");
        map.put("token", token);
        String gensalt = BCrypt.gensalt();
        System.err.println(gensalt);
        //加密

        List<User> list = userService.list();
        return new Result().data(map).msg("登陆成功").status(StatusCode.OK);
    }
}

